package com.dlwx.parttimetalent.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.base.BaseActivity;
import com.dlwx.parttimetalent.bean.BaseBean;
import com.dlwx.parttimetalent.bean.ImageBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.dlwx.parttimetalent.views.IdentityDialog;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class IdentityActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.image_header)
    CircleImageView imageHeader;
    @BindView(R.id.image_1)
    ImageView image1;
    @BindView(R.id.image_2)
    ImageView image2;
    @BindView(R.id.tv_exmple)
    TextView tvExmple;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.image_delete1)
    ImageView imageDelete1;
    @BindView(R.id.image_delete2)
    ImageView imageDelete2;
    private String imagePerson,imageCard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_identity);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        tvMiddleTitle.setText("身份证认证");
        tvMiddleTitle.setVisibility(View.VISIBLE);
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        String headUrl= (String) SPUtils.get(this,Constant.HEAD_URL,"");
        Glide.with(this).load(headUrl).into(imageHeader);
    }

    @OnClick({R.id.title_left_one_btn, R.id.image_header, R.id.image_1, R.id.image_2, R.id.tv_exmple, R.id.tv_confirm,
            R.id.image_delete1, R.id.image_delete2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                this.finish();
                break;
            case R.id.image_header:
                startPhoto(true, Constant.ONE);
                break;
            case R.id.image_1:
                startPhoto(false, Constant.TWO);
                break;
            case R.id.image_2:
                startPhoto(false, Constant.THREE);
                break;
            case R.id.tv_exmple:
                IdentityDialog dialog = new IdentityDialog(this, Constant.ZERO);
                dialog.show();
                break;
            case R.id.tv_confirm:
                checkInputDatas();
                break;
            case R.id.image_delete1:
                image1.setImageResource(R.mipmap.icon_shangchuantianjia);
                break;
            case R.id.image_delete2:
                image2.setImageResource(R.mipmap.icon_shangchuantianjia);
                break;
        }
    }




    private void checkInputDatas() {
        String name=etName.getText().toString();
        String num=etNum.getText().toString();
        if(TextUtils.isEmpty(name)){
            ToastUtils.toastForShort(this,"名字不能为空");
            return;
        }
        if(TextUtils.isEmpty(num)){
            ToastUtils.toastForShort(this,"身份证号码不能为空");
            return;
        }
        if(TextUtils.isEmpty(imagePerson)||TextUtils.isEmpty(imageCard)){
            ToastUtils.toastForShort(this,"照片必须上传齐全");
            return;
        }
        confirm(name,num);
    }
    private void confirm(String name, String num) {
        loadingDialog.show();
        OkgoUtil.post(Http.SubAuthData, this)
                .params("authType",2)
                .params("title1",name)
                .params("title2",num)
                .params("img1",imagePerson)
                .params("img2",imageCard)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        BaseBean parentBean = DealResult.getInstance().dealDatas(IdentityActivity.this, response, new TypeToken<BaseBean>() {}.getType());
                        if (parentBean == null) {
                            return;
                        }
                        if(parentBean.getCode()==Constant.SUCESS){
                            IdentityActivity.this.finish();
                        }
                        ToastUtils.toastForShort(IdentityActivity.this, parentBean.getResult());
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                        ToastUtils.toastForShort(IdentityActivity.this,getString(R.string.bad_net));
                    }
                });
    }


    private void startPhoto(boolean crop, int type) {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(IdentityActivity.this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(1)// 最大图片选择数量 int
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .enableCrop(crop)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .openClickSound(true)// 是否开启点击声音 true or false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                .forResult(type);//结果回调onActivityResult code

//                .theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
//                .minSelectNum(1)// 最小选择数量 int
//                .imageSpanCount(4)// 每行显示个数 int
//                .selectionMode()// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
//                .previewVideo()// 是否可预览视频 true or false
//                .enablePreviewAudio() // 是否可播放音频 true or false
//                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
//                .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
//                .isGif()// 是否显示gif图片 true or false
//                .compressSavePath(getPath())//压缩图片保存地址
//                .showCropFrame()// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
//                .showCropGrid()// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
//                .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
//                .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
//                .cropCompressQuality()// 裁剪压缩质量 默认90 int
//                .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
//                .videoQuality()// 视频录制质量 0 or 1 int
//                .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
//                .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
//                .recordVideoSecond()//视频秒数录制 默认60s int
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            if(selectList.isEmpty()){return;}
            LocalMedia media = selectList.get(0);
            File f;
            if(media.isCompressed()){
//                        Glide.with(SetAgeActivity.this).load(media.getCompressPath()).into(imageHeader);
                f=new File(media.getCompressPath());
            }else{
                f=new File(media.getPath());
            }
            switch (requestCode) {
                case Constant.ONE:
                    // 图片选择结果回调
                    upload(f,Constant.ONE,"head");
                    break;
                case Constant.TWO:
                    upload(f,Constant.TWO,"auth");
                    break;
                case Constant.THREE:
                    upload(f,Constant.THREE,"auth");
                    break;
            }
        }
    }


    private void upload(File f, final int msgSys,String type){
        loadingDialog.show();
        OkgoUtil.post(Http.UPLOAD_IMAGE,this)
                .params("type",type)
                .params("images",f)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        ImageBean parentBean= DealResult.getInstance().dealDatas(IdentityActivity.this,response,new TypeToken<ImageBean>() {}.getType());
                        if(parentBean==null){return;}
                        if(parentBean.getCode()== Constant.SUCESS){
                            ImageBean.BodyBean bean = parentBean.getBody();
                            switch (msgSys) {
                                case Constant.ONE:
                                Glide.with(IdentityActivity.this).load(bean.getImageurl()).into(imageHeader);
                                    break;
                                case Constant.TWO:
                                    imagePerson=bean.getImageurl();
                                    Glide.with(IdentityActivity.this).load(bean.getImageurl()).into(image1);
                                    break;
                                case Constant.THREE:
                                    imageCard=bean.getImageurl();
                                    Glide.with(IdentityActivity.this).load(bean.getImageurl()).into(image2);
                                    break;
                            }
                        }else {
                            ToastUtils.toastForShort(IdentityActivity.this,parentBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                    }
                });
    }

}
